import {defineStore} from 'pinia';
import {registerMicroApps, start, initGlobalState, type MicroAppStateActions} from 'qiankun';
import {store} from '@/models/index';
import {appConfig} from '@/config/appConfig';
import type {MicroState} from './types';

const initialState: MicroState = {
  data: {},
  router: {},
  qiankun: {},
  messageChange: {},
  microList: {},
  loadingMicro: false,
};

export const useMicroApp = defineStore('microAppStore', {
  state: (): MicroState => initialState,
  actions: {
    microBoot() {
      start({
        sandbox: {
          experimentalStyleIsolation: true,
        },
      });
    },
    // 一次性注册全部系统
    register(asyncConfig: any = appConfig) {
      // const microList = this.microList;
      // const loadingMicro = this.loadingMicro;
      // asyncConfig.forEach((o: any) => {
      //   o.props = {
      //     routerBase: o.activeRule,
      //     mainService: {
      //       loadingMicro,
      //       microList,
      //     },
      //   };
      // });
      // const that = this;
      registerMicroApps(asyncConfig, {
        beforeLoad: (app: any): any => {
          // that.loadingMicro = true
          console.log('before load app.name====>>>>>', app.name);
        },
        beforeMount: [
          (app: any): any => {
            console.log('[LifeCycle] before mount %c%s', 'color: green;', app.name);
          },
        ],
        afterMount: [
          (app: any): any => {
            // that.loadingMicro = false
            console.log('[LifeCycle] after mount %c%s', 'color: green;', app.name);
          },
        ],
        afterUnmount: [
          (app: any): any => {
            console.log('[LifeCycle] after unmount %c%s', 'color: green;', app.name);
          },
        ],
      });
      this.initMicroState();
      this.microBoot();
    },
    // 注册系统全局props属性
    initMicroState() {
      this.qiankun.actions = initGlobalState(initialState);
      this.qiankun.actions.onGlobalStateChange((state: any, prev: any) => {
        // state: 变更后的状态; prev 变更前的状态
        console.log('之前的数据', prev);
        console.log('最新的数据', state);
      });
      this.qiankun.actions.setGlobalState(initialState);
      this.qiankun.actions.offGlobalStateChange();
    },
    changeState<T>(name: string, value: T) {
      this.qiankun.actions.setGlobalState({[name]: value});
    },
  },
});
export function useMicroAppHook() {
  return useMicroApp(store);
}
